/*
 * @Author: silence
 * @Date: 2023-06-30 08:57:58
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-11-06 15:03:18
 * @Description: 电站设置页
 */
import 'package:ems_neutral_app/base/SilScaffold.dart';
import 'package:ems_neutral_app/pages/Mine/Language/SilLocalizations/SilLocalizations.dart';
import 'package:ems_neutral_app/pages/PowerStation/Controller/PowerStationController.dart';
import 'package:ems_neutral_app/utils/color/ColorUtils.dart';
import 'package:ems_neutral_app/utils/eventBus/eventBus.dart';
import 'package:ems_neutral_app/utils/string/StringConstant.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';
import 'package:sil_utils_package/utils/time/SilTimeUtils.dart';
import '../../../common/widgets/cubitWidget/SubmitBtn.dart';
import '../../../main.dart';
import 'PsSetCenterView.dart';
import 'PsSetStepLineChartView.dart';
import 'PsSetTopBgView.dart';

class PowerStationSetPage extends StatefulWidget {
  const PowerStationSetPage({super.key});

  @override
  State<PowerStationSetPage> createState() => _PowerStationSetPageState();
}

class _PowerStationSetPageState extends State<PowerStationSetPage>
    with RouteAware {
  bool _isShowPrice = true;
  PowerStationController _powerStationController =
      Get.put(PowerStationController());
  late ValueKey _setCenterViewKey;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  @override
  void dispose() {
    super.dispose();
    routeObserver.unsubscribe(this);
  }

  @override
  void didPopNext() {
    final route = ModalRoute.of(context)?.settings.name;
    print('返回到当前页面 A-didPopNext route: $route');

    /// 获取设备数据
    // initData();
  }

  @override
  void didPushNext() {
    final route = ModalRoute.of(context)?.settings.name;
    print('从当前页面跳到其他页面 route: $route');
  }

  @override
  void didPop() {
    final route = ModalRoute.of(context)?.settings.name;
    print('当前页面关闭 A-didPop route: $route');
  }

  @override
  void initState() {
    super.initState();

    /// 打开最新电价折线图（没有数据，则不展示）
    bus.on(StringConstant.OpenLatestElectricityPriceChart, (value) {
      _isShowPrice = value[0];
      if (this.mounted) setState(() {});
    });

    /// 选择的设备发生了改变
    bus.on(StringConstant.SelectDeviceChange, (arg) {
      initData();
    });

    /// tabbar回到设置页
    bus.on(StringConstant.APPGotoTabbar, (index) {
      if (index == 1) {
        _isShowPrice = true; // 再次返回电站设置，打开最新电价折线图（没有数据，则不展示）
        initData();
      }
    });

    _setCenterViewKey = ValueKey(SilTimeUtils.currentTimeMillis());
  }

  initData() {
    if (!this.mounted) return;

    /// 获取电站设置信息
    _powerStationController.getPowerStationSetInfo(
      context,
      successHandler: (p0) {
        _setCenterViewKey = ValueKey(SilTimeUtils.currentTimeMillis());
        setState(() {});
      },
      showLoading: true,
    );

    /// 获取最新电价数据
    _powerStationController.getLatestElectricityPrice(context);
  }

  @override
  Widget build(BuildContext context) {
    return SilScaffold(
      navBarHide: true,
      sideMargin: 0,
      backgroundColor: ColorUtils.hexColor('#010101'),
      body: mainWidget(),
      // floatingActionButton: FloatingActionButton(
      //   backgroundColor: ColorUtils.color_theme,
      //   child: SilText('Save'),
      //   onPressed: () {},
      // )
    );
  }

  mainWidget() {
    return Stack(
      children: [
        contentView(),

        /// 是否显示电价chart
        if (_isShowPrice == true)
          PsSetStepLineChartView(
            closeChartFunc: () {
              setState(() {
                _isShowPrice = !_isShowPrice;
              });
            },
          ),
      ],
    );
  }

  contentView() {
    return Container(
        decoration: BoxDecoration(
            gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
              ColorUtils.hexColor('#282828'),
              ColorUtils.hexColor('#010101')
            ])),
        child: CustomScrollView(
          slivers: [
            /// 顶部（是否卖电、工作模式）
            SliverToBoxAdapter(
              child: PsSetTopBgView(),
            ),
            SliverToBoxAdapter(
              child: PsSetCenterView(
                key: _setCenterViewKey,
              ),
            ),
            SliverToBoxAdapter(
              child: SubmitBtn(
                title: LangOf(context)?.power_setting?.save,
                onTapFunc: saveSetHandler,
              ),
            )
          ],
        ));
  }

  /// 保存设置
  saveSetHandler() {
    _powerStationController.savePowerStationSet(
      context,
      successHandler: (p0) {
        SilToast.show(p0.message);
      },
    );
  }
}
